package com.mf.morefun.ui.person;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.LocalListenBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.UserInfoBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestUserBean;
import com.mf.morefun.ui.HomePagerActivity;
import com.mf.morefun.ui.moreread.TestActivity;
import com.mf.morefun.ui.person.fragment.AchievementFragment;
import com.mf.morefun.ui.person.fragment.BookMarkFragment;
import com.mf.morefun.ui.person.fragment.PersonFraagment;
import com.mf.morefun.ui.person.fragment.WorksFragment;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.TransformationHomeUtils;
import com.mf.morefun.widget.TransformationMineUtils;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;
import com.zhcx.zhcxlibrary.widget.ChooseDialog;

import org.jetbrains.annotations.Nullable;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.support.constraint.Constraints.TAG;

public class MineInfoActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_star)
    TextView tvStar;
    @BindView(R.id.tv_flower)
    TextView tvFlower;
    @BindView(R.id.tv_trophy)
    TextView tvTrophy;
    @BindView(R.id.iv_works)
    ImageView ivWorks;
    @BindView(R.id.tv_works)
    TextView tvWorks;
    @BindView(R.id.ll_works)
    LinearLayout llWorks;
    @BindView(R.id.iv_achievement)
    ImageView ivAchievement;
    @BindView(R.id.tv_achievement)
    TextView tvAchievement;
    @BindView(R.id.ll_achievement)
    LinearLayout llAchievement;
    @BindView(R.id.iv_bookmark)
    ImageView ivBookmark;
    @BindView(R.id.tv_bookmark)
    TextView tvBookmark;
    @BindView(R.id.ll_bookmark)
    LinearLayout llBookmark;
    @BindView(R.id.iv_person)
    ImageView ivPerson;
    @BindView(R.id.tv_person)
    TextView tvPerson;
    @BindView(R.id.ll_person)
    LinearLayout llPerson;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.tv_clear)
    TextView tvClear;
    @BindView(R.id.ll_clear)
    LinearLayout llClear;
    @BindView(R.id.iv_logout)
    ImageView ivLogout;
    @BindView(R.id.tv_logout)
    TextView tvLogout;
    @BindView(R.id.ll_logout)
    LinearLayout llLogout;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    private SPUtils spUtils;
    private FragmentManager fManager;
    private WorksFragment mWorksFragment;//作品
    private AchievementFragment mAchievementFragment;//成就
    private BookMarkFragment mBookMarkFragment;//书签
    private PersonFraagment mPersonFraagment;//信息
    private DbManager mDbManager;


    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_mineinfo;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mDbManager = x.getDb(MoreFunApplication.daoConfig);
        spUtils = new SPUtils(getApplicationContext());
        fManager = getSupportFragmentManager();
        if (!IsLoginBean.isNo(false)){
            GetUserInfo.initLogin(spUtils.getString(Configuration.USERPHONE), spUtils.getString(Configuration.USERPASSWORD));
        }else {
            tvStar.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getStars() + "");
            tvFlower.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getFlows() + "");
            tvTrophy.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getMerits() + "");
            selectItem(0);
            changeButtonColor(0);
        }
        initGetUser(spUtils.getString(Configuration.USERID));
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("GETUSERINFO");
        registerReceiver(mReceiver, mFilter);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("GETUSERINFO")){
                tvStar.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getStars() + "");
                tvFlower.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getFlows() + "");
                tvTrophy.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getMerits() + "");
                selectItem(0);
                changeButtonColor(0);
            }
        }
    };
    private void initGetUser(String userId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.USERINFO);
        RequestUserBean userBean = new RequestUserBean();
        userBean.setId(userId);
        params.setBodyContent(JSON.toJSONString(userBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(mResult.getResult())){
                            UserInfoBean user = JSON.parseObject(mResult.getResult(), UserInfoBean.class);
                            if (null != user.getUserFinance()){
                                tvStar.setText(user.getUserFinance().getStars() + "");
                                tvFlower.setText(user.getUserFinance().getFlows() + "");
                                tvTrophy.setText(user.getUserFinance().getEnergyStones() + "");
                            }
                        }
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (IsLoginBean.isNo(false)){
            tvName.setText(MoreFunApplication.loginBean.getResult().getName());
            showCicleImg();
        }
    }

    //切换fragment的方法
    private int mIndex = -1;

    private void selectItem(int index) {
        FragmentTransaction transaction = fManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (mIndex == 0) {
                    return;
                }
                mIndex = 0;
                if (mWorksFragment == null) {
                    mWorksFragment = new WorksFragment();
                    transaction.add(R.id.fl_content, mWorksFragment);
                } else {
                    transaction.show(mWorksFragment);
                }
                break;
            case 1:
                if (mIndex == 1) {
                    return;
                }
                mIndex = 1;
                if (mAchievementFragment == null) {
                    mAchievementFragment = new AchievementFragment();
                    transaction.add(R.id.fl_content, mAchievementFragment);
                } else {
                    transaction.show(mAchievementFragment);
                }
                break;
            case 2:
                if (mIndex == 2) {
                    return;
                }
                mIndex = 2;
                if (mBookMarkFragment == null) {
                    mBookMarkFragment = new BookMarkFragment();
                    transaction.add(R.id.fl_content, mBookMarkFragment);
                } else {
                    transaction.show(mBookMarkFragment);
                }
                break;
            case 3:
                if (mIndex == 3) {
                    return;
                }
                mIndex = 3;
                if (mPersonFraagment == null) {
                    mPersonFraagment = new PersonFraagment();
                    transaction.add(R.id.fl_content, mPersonFraagment);
                } else {
                    transaction.show(mPersonFraagment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mWorksFragment != null) {
            transaction.hide(mWorksFragment);
        }
        if (mAchievementFragment != null) {
            transaction.hide(mAchievementFragment);
        }
        if (mBookMarkFragment != null) {
            transaction.hide(mBookMarkFragment);
        }
        if (mPersonFraagment != null) {
            transaction.hide(mPersonFraagment);
        }
    }

    private void showCicleImg() {
        CircleCrop circleCrop = new CircleCrop();
        RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
        Glide.with(MineInfoActivity.this).asBitmap().load(MoreFunApplication.loginBean.getResult().getHeadPortrait()).listener(new mRequestListener(ivHead)).apply(options).into(new TransformationMineUtils(ivHead, MineInfoActivity.this));
    }

    private class mRequestListener implements RequestListener {
        private ImageView ivPersonhead;
        public mRequestListener (ImageView ivPersonhead){
            this.ivPersonhead = ivPersonhead;
        }
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            Log.d(TAG, "onException: " + e.toString()+"  model:"+model+" isFirstResource: "+isFirstResource);
            Message msg = new Message();
            msg.what = 100;
            msg.obj = ivPersonhead;
            mHandler.sendMessage(msg);
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            Log.e(TAG,  "model:"+model+" isFirstResource: "+isFirstResource);
            return false;
        }
    };


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 100:
                    CircleCrop circleCrop = new CircleCrop();
                    RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
                    Glide.with(MineInfoActivity.this).asBitmap().load(R.mipmap.mine_user_icon).apply(options).into(new TransformationMineUtils((ImageView)msg.obj, MineInfoActivity.this));
                    break;
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(MineInfoActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_back, R.id.ll_works, R.id.ll_achievement, R.id.ll_bookmark, R.id.ll_person, R.id.ll_logout, R.id.ll_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_works:
                selectItem(0);
                changeButtonColor(0);
                break;
            case R.id.ll_achievement:
                selectItem(1);
                changeButtonColor(1);
                break;
            case R.id.ll_bookmark:
                selectItem(2);
                changeButtonColor(2);
                break;
            case R.id.ll_person:
                selectItem(3);
                changeButtonColor(3);
                break;
            case R.id.ll_logout:
                BackIdeaPop pop = new BackIdeaPop(MineInfoActivity.this);
                pop.showPop("确定要退出登录吗?", 0, 0);
                break;
            case R.id.ll_clear:
                //
                BackIdeaPop pops = new BackIdeaPop(MineInfoActivity.this);
                pops.showPop("确定要清除缓存吗?", 1, 0);
                break;
        }
    }

    public String getBasePath() {
        String strPath = null;
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            strPath = getApplicationContext().getFilesDir() + "/" + "lameMp3";
        } else {
            strPath = Environment.getExternalStorageDirectory() + "/" + "lameMp3";
        }
        File dir = new File(strPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return strPath;
    }

    /**
     * 删除文件，可以是文件或文件夹
     *
     * @param fileName 要删除的文件名
     * @return 删除成功返回true，否则返回false
     */
    public boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            if (file.isFile())
                return deleteFile(fileName);
            else
                return deleteDirectory(fileName);
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }


    private void changeButtonColor(int index) {
        switch (index) {
            case 0:
                ivWorks.setImageResource(R.mipmap.mine_yes_works_icon);
                tvWorks.setTextColor(getResources().getColor(R.color.white));
                llWorks.setBackgroundResource(R.mipmap.mineselected);
                ivAchievement.setImageResource(R.mipmap.mine_not_achievement_icon);
                tvAchievement.setTextColor(0xff999999);
                llAchievement.setBackgroundResource(R.mipmap.noselect);
                ivBookmark.setImageResource(R.mipmap.mine_not_bookmark_icon);
                tvBookmark.setTextColor(0xff999999);
                llBookmark.setBackgroundResource(R.mipmap.noselect);
                ivPerson.setImageResource(R.mipmap.mine_not_collection_icon);
                tvPerson.setTextColor(0xff999999);
                llPerson.setBackgroundResource(R.mipmap.noselect);
                tvClear.setTextColor(0xff999999);
                llClear.setBackgroundResource(R.mipmap.noselect);
                tvLogout.setTextColor(0xff999999);
                llLogout.setBackgroundResource(R.mipmap.noselect);
                break;
            case 1:
                ivWorks.setImageResource(R.mipmap.mine_not_works_icon);
                tvWorks.setTextColor(0xff999999);
                llWorks.setBackgroundResource(R.mipmap.noselect);
                ivAchievement.setImageResource(R.mipmap.mine_yes_achievement_icon);
                tvAchievement.setTextColor(getResources().getColor(R.color.white));
                llAchievement.setBackgroundResource(R.mipmap.mineselected);
                ivBookmark.setImageResource(R.mipmap.mine_not_bookmark_icon);
                tvBookmark.setTextColor(0xff999999);
                llBookmark.setBackgroundResource(R.mipmap.noselect);
                ivPerson.setImageResource(R.mipmap.mine_not_collection_icon);
                tvPerson.setTextColor(0xff999999);
                llPerson.setBackgroundResource(R.mipmap.noselect);
                tvClear.setTextColor(0xff999999);
                llClear.setBackgroundResource(R.mipmap.noselect);
                tvLogout.setTextColor(0xff999999);
                llLogout.setBackgroundResource(R.mipmap.noselect);
                break;
            case 2:
                ivWorks.setImageResource(R.mipmap.mine_not_works_icon);
                tvWorks.setTextColor(0xff999999);
                llWorks.setBackgroundResource(R.mipmap.noselect);
                ivAchievement.setImageResource(R.mipmap.mine_not_achievement_icon);
                tvAchievement.setTextColor(0xff999999);
                llAchievement.setBackgroundResource(R.mipmap.noselect);
                ivBookmark.setImageResource(R.mipmap.mine_yes_bookmark_icon);
                tvBookmark.setTextColor(getResources().getColor(R.color.white));
                llBookmark.setBackgroundResource(R.mipmap.mineselected);
                ivPerson.setImageResource(R.mipmap.mine_not_collection_icon);
                tvPerson.setTextColor(0xff999999);
                llPerson.setBackgroundResource(R.mipmap.noselect);
                tvClear.setTextColor(0xff999999);
                llClear.setBackgroundResource(R.mipmap.noselect);
                tvLogout.setTextColor(0xff999999);
                llLogout.setBackgroundResource(R.mipmap.noselect);
                break;
            case 3:
                ivWorks.setImageResource(R.mipmap.mine_not_works_icon);
                tvWorks.setTextColor(0xff999999);
                llWorks.setBackgroundResource(R.mipmap.noselect);
                ivAchievement.setImageResource(R.mipmap.mine_not_achievement_icon);
                tvAchievement.setTextColor(0xff999999);
                llAchievement.setBackgroundResource(R.mipmap.noselect);
                ivBookmark.setImageResource(R.mipmap.mine_not_bookmark_icon);
                tvBookmark.setTextColor(0xff999999);
                llBookmark.setBackgroundResource(R.mipmap.noselect);
                ivPerson.setImageResource(R.mipmap.mine_yes_collection_icon);
                tvPerson.setTextColor(getResources().getColor(R.color.white));
                llPerson.setBackgroundResource(R.mipmap.mineselected);
                tvClear.setTextColor(0xff999999);
                llClear.setBackgroundResource(R.mipmap.noselect);
                tvLogout.setTextColor(0xff999999);
                llLogout.setBackgroundResource(R.mipmap.noselect);
                break;
            case 4:
                ivWorks.setImageResource(R.mipmap.mine_yes_works_icon);
                tvWorks.setTextColor(getResources().getColor(R.color.white));
                llWorks.setBackgroundResource(R.mipmap.mineselected);
                ivAchievement.setImageResource(R.mipmap.mine_not_achievement_icon);
                tvAchievement.setTextColor(0xff999999);
                llAchievement.setBackgroundResource(R.mipmap.noselect);
                ivBookmark.setImageResource(R.mipmap.mine_not_bookmark_icon);
                tvBookmark.setTextColor(0xff999999);
                llBookmark.setBackgroundResource(R.mipmap.noselect);
                ivPerson.setImageResource(R.mipmap.mine_not_collection_icon);
                tvPerson.setTextColor(0xff999999);
                llPerson.setBackgroundResource(R.mipmap.noselect);
                tvClear.setTextColor(getResources().getColor(R.color.white));
                llClear.setBackgroundResource(R.mipmap.mineselected);
                tvLogout.setTextColor(0xff999999);
                llLogout.setBackgroundResource(R.mipmap.noselect);
                break;
            case 5:
                ivWorks.setImageResource(R.mipmap.mine_yes_works_icon);
                tvWorks.setTextColor(0xff999999);
                llWorks.setBackgroundResource(R.mipmap.noselect);
                ivAchievement.setImageResource(R.mipmap.mine_not_achievement_icon);
                tvAchievement.setTextColor(0xff999999);
                llAchievement.setBackgroundResource(R.mipmap.noselect);
                ivBookmark.setImageResource(R.mipmap.mine_not_bookmark_icon);
                tvBookmark.setTextColor(0xff999999);
                llBookmark.setBackgroundResource(R.mipmap.noselect);
                ivPerson.setImageResource(R.mipmap.mine_not_collection_icon);
                tvPerson.setTextColor(0xff999999);
                llPerson.setBackgroundResource(R.mipmap.noselect);
                tvClear.setTextColor(0xff999999);
                llClear.setBackgroundResource(R.mipmap.noselect);
                tvLogout.setTextColor(getResources().getColor(R.color.white));
                llLogout.setBackgroundResource(R.mipmap.mineselected);
                break;
        }
    }
}
